package com.rfid.udp;

import android.os.Build;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class UdpManager {

    private Executor mExecutor = Executors.newCachedThreadPool();

    private boolean broadcasting = false;
    private boolean listening = false;
    static UdpManager manager;
    private UdpListener mUdpListener;
    private DatagramSocket mServerSocket;
    private static final String PHONE_INFO = Build.BRAND + "_" + Build.MODEL;

    public static UdpManager getInstance() {
        if (manager == null) {
            manager = new UdpManager();
        }
        return manager;
    }

    public void listening(UdpListener listener) throws SocketException {
        mUdpListener = listener;
        if (listening) {
            return;
        }
        listening = true;
        final DatagramSocket socket=new DatagramSocket(9898);
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                mServerSocket = socket;
                byte[] buffer=new byte[1024*64];
                DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
                while(listening) {
                    try {
                        socket.receive(packet);
                        int len = packet.getLength();
                        String rs = new String(buffer, 0, len);
                        if (rs.startsWith("rfid-")) {
                            String spls[] = rs.split("-");
                            String message = spls[1];
                            String pinfo = "";
                            if (spls.length > 2) {
                                pinfo =  spls[2];
                            }
                            String ip = packet.getAddress().getHostAddress();
                            if (mUdpListener != null) {
                                mUdpListener.onReceived(message,pinfo,ip);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        listening = false;
                    }
                }
            }
        });
    }

    public boolean isListening() {
        return listening;
    }

    public void startBroadcastSelf(final String text) {
        if (broadcasting) {
            return;
        }
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                broadcasting = true;
                while(broadcasting) {
                    try{
                        DatagramSocket socket=new DatagramSocket();
                        byte[] buffer=("rfid-"+text + "-" + PHONE_INFO).getBytes();
                        DatagramPacket packet=new DatagramPacket(buffer,buffer.length, InetAddress.getByName("255.255.255.255"),9898);
                        socket.send(packet);
                        socket.close();
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void destroy() {
        broadcasting = false;
        listening = false;
        if (mServerSocket != null) {
            mServerSocket.close();
        }
    }
}
